//
//  SQBProfitViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/7.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "SQBProfitViewController.h"
#import "SQBProfitCell.h"
#import "SQBProfitModel.h"

@interface SQBProfitViewController ()<UITableViewDataSource,UITableViewDelegate,HTTPClientDelegate>
{
    NSMutableArray *_dataArray;
}
@property (weak, nonatomic) IBOutlet UILabel *profitAmoutValue;
@property (weak, nonatomic) IBOutlet UILabel *profitAmoutLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) BOOL          isLoading;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, assign) NSInteger     currPage;
@property (nonatomic, assign) NSInteger     totalCount;
@end

@implementation SQBProfitViewController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self initNavBarTitle:@"随取宝收益明细" andLeftItemName:@"返回" andRightItemName:@""];
    
    [self initData];
    [self initView];
}

#pragma mark - TableView
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    TradeDetailViewController *tradeDetail = [[TradeDetailViewController alloc] init];
    //    [self.navigationController pushViewController:tradeDetail animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _dataArray.count>0?_dataArray.count:1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_dataArray.count) {
        NSArray *subArray = _dataArray[section];
        return subArray.count;
    }else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_dataArray.count) {
        static NSString *cellID = @"cellID";
        SQBProfitCell *cell = [_tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[NSBundle mainBundle] loadNibNamed:@"SQBProfitCell" owner:self options:nil][0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell refreshCellWithModel:_dataArray[indexPath.section][indexPath.row]];
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, KAdaptNum(44));
        return cell;
    }else {
        EmptyTableViewCell *cell = [[EmptyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"emptyCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.backgroundColor = KbackgroundColor;
        
        cell.frame=CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, _tableView.frame.size.height);
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self tableView:tableView cellForRowAtIndexPath:indexPath].frame.size.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (_dataArray.count) {
        return KAdaptNum(30.0);
    }else {
        return CGFLOAT_MIN;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (_dataArray.count) {
        UIView *headerView = [UIView viewWithFrame:RECTMAKE(0, 0, MSWIDTH, KAdaptNum(30)) backgroundColor:KbackgroundColor superview:nil];
        
        SQBProfitModel *model = _dataArray[section][0];
        
        [UILabel labelWithFrame:RECTMAKE(10, 0, MSWIDTH - 100, GetHeight(headerView)) text:model.month textColor:KGrayColor textFont:13 fitWidth:NO superview:headerView];
        
        UILabel *profitValue = [UILabel labelWithFrame:RECTMAKE(MSWIDTH - 10 - 80, 0, 80, GetHeight(headerView)) text:@"收益(元)" textColor:KGrayColor textFont:13 fitWidth:NO superview:headerView];
        profitValue.textAlignment = NSTextAlignmentRight;
        
        return headerView;
    }else {
        return nil;
    }
}

#pragma mark - Data
- (void)initData {
    _dataArray = [NSMutableArray array];
    
}


- (void)requestData {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"511" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    [parameters setObject:[NSString stringWithFormat:@"%ld",(long)_currPage] forKey:@"currPage"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters withViewController:self];
}


#pragma - 网络数据回调代理
- (void)startRequest {
    _isLoading = YES;
}

// 返回成功
- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    [self hiddenRefreshView];
    NSDictionary *dics = obj;
    DLOG(@"dic=%@",dics);
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        _profitAmoutLabel.text = [NSString stringWithFormat:@"%@",[CommonClass formatConversion:[[dics objectForKey:@"totalAmount"] doubleValue] type:0]];
        
        if (_currPage == 1) {
            [_dataArray removeAllObjects];
        }
        NSArray *list = dics[@"list"];
        if (list.count) {
            for (NSDictionary *subDict in list) {
                BOOL isNew = NO;
                
                SQBProfitModel *model = [SQBProfitModel objectWithKeyValues:subDict];
                model.Time = [NSString converDate:[subDict[@"time"] objectForKey:@"time"] withFormat:@"MM-dd hh:mm"];
                model.month = [NSString converDate:[subDict[@"time"] objectForKey:@"time"] withFormat:@"yyyy年MM月"];
                model.day = [NSString converDate:[subDict[@"time"] objectForKey:@"time"] withFormat:@"dd日"];
                if (_dataArray.count <= 0) {
                    NSMutableArray *firstArr = [NSMutableArray array];
                    [firstArr addObject:model];
                    [_dataArray addObject:firstArr];
                }else {
                    for (NSInteger i=0; i < _dataArray.count; i++) {
                        
                        NSMutableArray *subArr = _dataArray[i];
                        
                        for (NSInteger j=0; j < subArr.count; j++) {
                            
                            SQBProfitModel *subModel = subArr[j];
                            if ([subModel.month isEqualToString:model.month]) {
                                [subArr addObject:model];
                                break;
                            }
                            
                            if (i==_dataArray.count-1 && j==subArr.count-1) {
                                isNew = YES;
                            }
                        }
                    }
                    if (isNew == YES) {
                        NSMutableArray *otherArr = [NSMutableArray array];
                        [otherArr addObject:model];
                        [_dataArray addObject:otherArr];
                        
                        isNew = NO;
                    }
                }
            }
        }
        
        [_tableView reloadData];
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else {
        
        [SVProgressHUD showImage:nil status:[dics objectForKey:@"msg"]];
    }
    
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    [self hiddenRefreshView];
}

// 无可用的网络
- (void)networkError {
    //  [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
    _isLoading = NO;
    [self hiddenRefreshView];
}

#pragma mark - 重新加载
- (void)reloadRequest
{
    [self headerRereshing];
}

#pragma mark - 刷新
- (void)headerRereshing {
    _currPage = 1;
    [self requestData];
}

- (void)footerRereshing {
    _currPage ++;
    [self requestData];
}

- (void)hiddenRefreshView {
    if (!_tableView.mj_header.hidden) {
        [_tableView.mj_header endRefreshing];
    }
    if (!_tableView.mj_footer.hidden) {
        [_tableView.mj_footer endRefreshing];
    }
}

#pragma mark - View
- (void)initView {
    _profitAmoutValue.font = KFontSize(13);
    _profitAmoutLabel.font = KFontSize(36);
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.estimatedRowHeight = KAdaptNum(44);
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    _tableView.mj_header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    // 自动刷新(一进入程序就下拉刷新)
    //    [self.tableView headerBeginRefreshing];
     [_tableView.mj_header beginRefreshing];
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
     _tableView.mj_footer = [MJRefreshBackNormalFooter  footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
   
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
